/**
 * Created with JetBrains WebStorm.
 * User: Tomer
 * Date: 1/17/13
 * Time: 1:55  To change this template use File | Settings | File Templates.
 */

function ChatCtrl($scope, $timeout,$location,$rootScope){
/*
    $("#textInput").bind( 'keydown', function(e) {
        if ((e.keyCode || e.charCode) !== 13) return true;
        $("#sendMessageButton").click();
        return false;
    });
    */

    var ctrl_pubnub = null;

    var initChat = function (){

        $scope.message = Object();
        $scope.messages = [];
        $scope.channel = globalAppParams.channel;
        $scope.nickname = globalAppParams.name ;
        $scope.userId = globalAppParams.userId;
        $scope.photoId = globalAppParams.photoId;
        $scope.limit = 10;
        $scope.showMessageForm = true;

        ctrl_pubnub = PUBNUB.init({
            publish_key   : "pub-8e474368-7add-4283-9b87-caf9efbcdedc",
            subscribe_key : "sub-1ffec1f3-9463-11e1-9376-77819258e702",
            ssl           : false,
            origin        : "pubsub.pubnub.com"
        })


        ctrl_pubnub.subscribe({
            channel: $scope.channel,
            restore: false,

            callback: function (message) {
                $scope.$apply(function () {
                    $scope.messages.push(message);
     /*               if (message.userId != $scope.userId)
                    {
                        playSound('Msg');
                    }*/
                    $timeout(function(){
                            console.log("timed outttt");
                            $("#messages").scrollTop(
                                $("#messages")[0].scrollHeight
                        );
                    },0);
                });
            },

            disconnect: function () {
                $scope.$apply(function () {

                });
            },

            reconnect: function () {
                $scope.$apply(function () {

                });
            },

            connect: function () {
                $scope.$apply(function () {
                    $scope.history();
                });
            }


        });
    }

    $rootScope.$on('initChat', function() {
      ;
        initChat();
    });

    if ($location.$$path=='/chat') {
        initChat();
    }



    $scope.history = function () {
        ctrl_pubnub.history({
            channel: $scope.channel,
            limit: $scope.limit
        }, function (messages) {

            $scope.$apply(function () {
                $scope.messages = messages[0];
            });
            $timeout(function(){
                console.log("timed outttt");
                $("#messages").scrollTop(
                    $("#messages")[0].scrollHeight
                );
            },0);
        });
    };

    $scope.back = function() {
        $location.goBack();
    };

    $scope.goToSurvey = function() {
        $location.path('survey');
    };

    $scope.initSurvey = function(){
        $scope.survey = new SurveyObject();
        $scope.survey.answers = [];
    }

    $scope.initSurvey();

    $scope.addSurveyAnswer = function(){
        if ($scope.newSurveyAnswer == "" || typeof $scope.newSurveyAnswer === "undefined" )
        return;

        $scope.survey.answers.push($scope.newSurveyAnswer);
        $scope.newSurveyAnswer='';
    }

    $scope.removeSurveyAnswer = function( answerIndex ) {
        $scope.survey.answers.splice(answerIndex, 1);
    };


    $scope.sendSurvey = function () {

        console.log("survey was called");

        if ($scope.survey.answers.length == 0 || $scope.survey.question == "")
        return;

        var survey = new SurveyObject($scope.nickname, $scope.survey.question,$scope.survey.answers,0,'new');
        var tmpMsg = new PubNubMsgObject($scope.nickname, $scope.userId, $scope.photoId, "survey",currentTime(),'surveyTextFill',survey);
        sendPubNubMessage($scope.channel,tmpMsg);

        $scope.initSurvey();
        $location.path('chat');
    };

    $scope.getImageUrl = function(photoId)
    {
        if (photoId ==null || photoId == "null" || photoId == "none" || photoId == "")
        {
            return "content/img/img_profile_placeholder.png";
        }
        return "/image/serve?key="+ photoId;
    }

    $scope.timeFormatter = function (string){
        var ret="";
        if (string){
            var resultArray = string.split(":");
            ret=resultArray[0]+":"+resultArray[1];
        }
        return ret;
    }

    $scope.isMessage = function(message) {
        return (message.type == "message" || (message.type == "survey") || message.type == "image");
    };


    $scope.publish = function () {

        if ($scope.message.text == "")
        return;

        var tmpMsg =  new PubNubMsgObject($scope.nickname,$scope.userId, $scope.photoId, "message",currentTime(),$scope.message.text,null);
        console.log("tmpMsg");
        console.log(tmpMsg);

        sendPubNubMessage($scope.channel,tmpMsg);

        //reset the message text
        $scope.message.text = "";
    }

    function sendPubNubMessage(channel,message){
        ctrl_pubnub.publish({
                channel: channel,
                message: message
            }
        )};
}

function PubNubMsgObject(username,userId,photoId,type,time,text,survey,videoChat,image){
    // type - message, survey, videoChat, image
    this.username=username;
    this.type=type;
    this.text=text;
    this.time=time;
    this.userId = userId;
    this.photoId = photoId;
    if (survey) {
        this.survey=survey;
    }
    if (videoChat) {
        this.videoChat=videoChat;
    }
    if (image) {
        this.image=image;
    }
}

function SurveyObject(username, question,answers,answerid,status){
    //status - new, close, answer
    this.username=username;
    this.question=question;
    this.answers=answers;
    this.answerid=answerid;
    this.status=status;
}

function currentTime()
{
    var d = new Date();
    var seconds = d.getSeconds();
    seconds < 10 ? seconds = '0' + seconds : seconds;
    var minutes = d.getMinutes();
    minutes < 10 ? minutes = '0' + minutes : minutes;
    var hours = d.getHours();
    hours < 10 ? hours = '0' + hours : hours;
    var t = hours + ":" + minutes + ":" + seconds;
    return t;
}

function playSound(soundId,stopFlg) {
    console.log("play soundId"+soundId);
    if (stopFlg) {
        $("#notificationSounds"+soundId).trigger("pause");
    } else {
        $("#notificationSounds"+soundId).trigger("load");
        $("#notificationSounds"+soundId).trigger("play");
    }
}
